import axios from 'axios'
import { message } from "ant-design-vue";

axios.defaults.baseURL = process.env.VUE_APP_API_BASE_URL

/**
 * @description 统一导出excel方法
 */

export const exportExcel = (url, params, method = 'get', excelName = '数据导入', suffix = 'xlsx') => {
  let options = {
    url,
    method,
    responseType: 'blob',
    headers: {}
  }
  /// 权鉴相关
  const tokenKey = localStorage.getItem("token_key");
  const token = localStorage.getItem("token")
  if(token) options.headers.Authorization = token;
  if(tokenKey) options.headers["Authorization-key"] = tokenKey;
  if (options.method.toLocaleLowerCase() === 'get') {
    options.params = params
  } else {
    options.data = params
  }
  return new Promise((resolve, reject) => {
    axios(options).then(res => {
      /* 兼容ie内核，360浏览器的兼容模式 */
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        let blob = new Blob([res.data])
        window.navigator.msSaveOrOpenBlob(blob, `${excelName}.${suffix}`)
      } else {
      /* 火狐谷歌的文件下载方式 */
        var blob = new Blob([res.data])
        var downloadElement = document.createElement('a')
        var href = window.URL.createObjectURL(blob)
        downloadElement.href = href
        downloadElement.download = `${excelName}.${suffix}`
        document.body.appendChild(downloadElement)
        downloadElement.click()
        document.body.removeChild(downloadElement)
        window.URL.revokeObjectURL(href)
      }
      // window.open(`${location.origin}${url}`)
      resolve()
    }).catch(err => {
      console.log(err, 'err');
      message.error({
        content: "下载失败",
        duration: 1,
      });
      reject()
    })
  })
}
